package com.heima.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class ConsumerQuickStart {
    public static void main(String[] args) {
        //2. 根据idea的提示完成配置
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        //每个消费者都应该有自己的组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "heima1");
        //设置key和value的反序列话
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        //关闭自动提交
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

        //1. 创建消费者的核心对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        //3. 设置监听的topic
        consumer.subscribe(Collections.singletonList("itcast"));

        //4. 每隔一段时间从kakfa中拉取一次消息进行消费
        try {
            while (true){
                //每隔一秒钟拉取一次消息
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println(record.key() + " : " + record.value());

                    //手动的同步提交
                    //consumer.commitSync();
                }

                //手动异步提交
               /* consumer.commitAsync(new OffsetCommitCallback() {
                    @Override
                    public void onComplete(Map<TopicPartition, OffsetAndMetadata> map, Exception e) {
                        if(null != e){
                            e.printStackTrace();
                            consumer.commitAsync();
                        }
                    }
                });*/

                consumer.commitAsync();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            consumer.commitSync();

            consumer.close();
        }

    }
}
